package com.kaili.controller.pda.v1;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.db.service.IHsEwbSubService;
import com.kaili.db.service.IHsEwbsStowageDetailService;
import com.kaili.db.service.IHsOptEwbService;
import com.kaili.pojo.entity.HsEwbSub;
import com.kaili.pojo.entity.HsEwbsStowageDetail;
import com.kaili.pojo.entity.HsOptEwb;
import com.kaili.pojo.vo.EwbQueryVO;
import com.kaili.version.ApiVersion;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @AUTHOR pengdongxu.
 * @Date: 18-5-25 上午9:13.
 * @COPYRIGHT 杭州凯立
 */

@ApiVersion(1)
@RequestMapping("/{api_version}")
@RestController("arriveSendControllerP")
@Api(tags = "[pda]到件派送", description = "[pda]到件送货相关API")
public class ArriveSendController {

    @Autowired
    private IHsEwbSubService hsEwbSubService;
    @Autowired
    private IHsEwbsStowageDetailService ewbsStowageDetailService;
    @Autowired
    private IHsOptEwbService ewbService;

    @ApiOperation(value = "PDA通过子单获取主单详细信息")
    @GetMapping("/p/dispatchSubs/")
    public Map getEwbBySub(@Pattern(regexp = "^[A-Za-z0-9]{0,20}$",message = "运单应为[A-Za-z0-9]组成的1-20位字符")
                               @RequestParam("ewbSub") @ApiParam(value="托运单号",defaultValue = "0000011111")String ewbSub){
        HsEwbSub hsEwbSub = hsEwbSubService.selectEwbNo(ewbSub);
        if (null == hsEwbSub){
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("ewb_no", hsEwbSub.getEwbNo());
        List<HsEwbsStowageDetail> ewbsStowageDetails = ewbsStowageDetailService.queryEwbByStowage(map);
        Page<EwbQueryVO> pager = new Page<>();
        map.put("ewbNo", hsEwbSub.getEwbNo());
        pager = ewbService.queryEwbList(pager,map);
        int piece = pager.getRecords().get(0).getTotalPiece();
        int abnormalPiece = 0;
        for (HsEwbsStowageDetail stowageDetail : ewbsStowageDetails){
            if (stowageDetail.getAbnormalPiece()!=null && stowageDetail.getAbnormalPiece()!=0){
                abnormalPiece = abnormalPiece + stowageDetail.getAbnormalPiece();
            }
        }
        map.put("piece", piece);
        map.put("abnormalPiece", abnormalPiece);
        map.put("adress",pager.getRecords().get(0).getReceiveProvinceName()+
                pager.getRecords().get(0).getReceiveCityName()+
                pager.getRecords().get(0).getReceiveCountyName()+
                pager.getRecords().get(0).getReceiveCustomerAddress());
        return map;
    }
}
